import { createRouter, createWebHashHistory } from "vue-router";
import type { RouteRecordRaw } from "vue-router";
import type { App } from "vue";
import Layout from "@/layout/index.vue";

/**
 * 不重定向白名单
 */
export const NO_REDIRECT_WHITE_LIST = ["/login"];

/**
 * 不重置路由白名单
 */
export const NO_RESET_WHITE_LIST = ["Login", "NoFind", "Root"];

// 默认常用路由
export const constantRouterMap: AppRouteRecordRaw[] = [
  {
    path: "/",
    component: Layout,
    name: "Root",
    meta: {
      hidden: true,
    },
  },
  {
    path: "/login",
    component: () => import("@/views/login/login.vue"),
    name: "Login",
    meta: {
      hidden: true,
    },
  },
  {
    path: "/404",
    component: () => import("../views/error/404.vue"),
    name: "NoFind",
    meta: {
      hidden: true,
    },
  },
  {
    path: "/:pathMatch(.*)*",
    component: () => import("@/views/error/404.vue"),
    meta: {
      hidden: true,
    },
  },
];

// 权限路由
export const asyncRouterMap: AppRouteRecordRaw[] = [
  {
    path: "/user",
    component: Layout,
    name: "user",
    redirect: "/user/list",
    meta: {
      title: "用户管理",
      // 使用el 自带图标 前缀添加el
      icon: "el-menu",
    },
    children: [
      {
        path: "list",
        name: "user_list",
        component: () => import("@/views/user/user_list.vue"),
        meta: {
          title: "用户列表",
          // icon: "el-help-filled",
        },
      },
      {
        path: "auth",
        name: "user_auth",
        component: () => import("@/views/user/user_auth.vue"),
        meta: {
          title: "用户权限",
          icon: "vue",
          permission: ["admin"],
        },
      },
    ],
  },
];

const router = createRouter({
  // 创建一个history路由模式 带# 模式 history模式
  history: createWebHashHistory(),
  // 启用「严格模式」，严格区分 URL 末尾的斜杠（/）
  // 启用后，/home 和 /home/ 会被视为两个不同的路由（前者匹配成功，后者匹配失败）。
  // 禁用（strict: false）时，两者会被视为相同路由（自动忽略末尾斜杠）。
  strict: true,
  // 指定初始路由规则数组
  routes: constantRouterMap as RouteRecordRaw[],
  // 控制路由切换时页面的滚动行为。
  scrollBehavior: (_to, _from, savedPosition) => {
    // 如果是返回上一页，恢复之前的滚动位置
    if (savedPosition) {
      return savedPosition;
    }
    // 否则滚动到顶部
    return { left: 0, top: 0 };
  },
});

// 重置路由实例，通常用于用户退出登录或权限变更时，清除动态添加的路由
export const resetRouter = (): void => {
  // 定义白名单路由
  const resetWhiteNameList = NO_RESET_WHITE_LIST;
  // 遍历所有已注册路由
  router.getRoutes().forEach((route) => {
    const { name } = route;
    // 判断并移除非白名单路由
    if (name && !resetWhiteNameList.includes(name as string)) {
      router.hasRoute(name) && router.removeRoute(name);
    }
  });
};

// 注册路由
export const setupRouter = (app: App<Element>) => {
  app.use(router);
};

export default router;
